package halberd.filter;

import halberd.DataType;
import halberd.ImgFilter;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;
import halberd.utils.RGBUtils;

/**
 * 
 * @author jiang
 *
 */
public class SobelFilter implements ImgFilter {
	public ImgData process(ImgData input) {
		if(!canProcess(input)) {
			return null;
		}
		ImgData result=ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		int[][][] ints=input.getDatas();
		sobel(ints,result.getDatas(),input.getWidth(),input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}
	private boolean canProcess(ImgData input) {
		if(input==null) {
			return false;
		}
		DataType dt=input.getDataType();
		if(dt==DataType.GRAY) {
			return true;
		}
		return false;
	}
	
	private void sobel(int[][][] src, int[][][] dst, int w, int h) {
		int[][] sobelx={{-1,-1,-1},{0,0,0},{1,1,1}};
		int[][] sobely={{-1,0,1},{-1,0,1},{-1,0,1}};
		//////////////////////////////
		for (int i = 1; i < w-1; i++)
	    {
	        for (int j = 1; j < h-1; j++)
	        {
	        	int x=0;
	        	int y=0;
				for(int m=-1,m0=0;m0<3;m0++,m++)
				{
					for(int n=-1,n0=0;n0<3;n0++,n++)
					{
						x+=sobelx[m0][n0]*src[i+m][j+n][4];
						y+=sobely[m0][n0]*src[i+m][j+n][4];
					}
				}
				double dr=Math.sqrt((double)(x*x+y*y));
				dst[i][j][4]=RGBUtils.clamp255((int)(255-dr));
			}
		}
	}
}
